package indigo.shiro.config;

import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import com.google.common.base.Strings;

public class ShiroAnnotationsAuthorizationRegistrar implements ImportBeanDefinitionRegistrar {
	public static final String DEFAULT_SECURITY_MANAGER_BEAN_NAME = "securityManager";

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		AnnotationAttributes attrs = AnnotationAttributes.fromMap(
				importingClassMetadata.getAnnotationAttributes(EnableShiroAnnotationsAuthorization.class.getName()));
		String securityManagerRef = Strings.emptyToNull(attrs.getString("securityManagerRef"));

		AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
				.genericBeanDefinition(AuthorizationAttributeSourceAdvisor.class)
				.addPropertyReference("securityManager", securityManagerRef)
				.getBeanDefinition();
		registry.registerBeanDefinition("authorizationAttributeSourceAdvisor", beanDefinition);
	}
}
